package com.luobr.backend.manage.websocket.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.luobr.backend.manage.websocket.model.ImageEditRequestMessage;
import com.luobr.backend.model.vo.user.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Component
@Slf4j
public class ImageEditEventProducer {

    @Resource
    Disruptor<ImageEditEvent> imageEditEventDisruptor;

    public void publishEvent(ImageEditRequestMessage imageEditRequestMessage, WebSocketSession session, UserLoginVO user, Long imageId) {
        RingBuffer<ImageEditEvent> ringBuffer = imageEditEventDisruptor.getRingBuffer();
        // 获取可以生成的位置
        long next = ringBuffer.next();
        ImageEditEvent imageEditEvent = ringBuffer.get(next);
        imageEditEvent.setSession(session);
        imageEditEvent.setImageEditRequestMessage(imageEditRequestMessage);
        imageEditEvent.setUser(user);
        imageEditEvent.setImageId(imageId);
        // 发布事件
        ringBuffer.publish(next);
    }

    /**
     * 优雅停机
     */
    @PreDestroy
    public void close() {
        imageEditEventDisruptor.shutdown();
    }
}
